<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>选项卡</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    li {
      list-style: none;
    }

    .container {
      margin: 50px auto;
      width: 400px;
      background: rgb(147, 143, 143);

    }

    .tabs {
      display: flex;
      border-bottom: 1px solid #000;
    }

    .tab {
      flex: 1;
      height: 30px;
      text-align: center;
      line-height: 30px;
      cursor: pointer;
    }

    .tab.active {
      background: #000;
      color: #fff;
    }

    .content-box section {
      height: 400px;
      display: none;
    }

    .content-box section.active {
      display: block;
    }
  </style>
</head>

<body>
  <div class="container">
    <ul class="tabs">
      <li class="tab active">标题1</li>
      <li class="tab">标题2</li>
      <li class="tab">标题3</li>
    </ul>

    <div class="content-box">
      <section class="active">标题1对应内容</section>
      <section>标题2对应内容</section>
      <section>标题3对应内容</section>
    </div>

  </div>
  <script>
    const tabs = document.querySelectorAll('.tab')
    const contents = document.querySelectorAll('.content-box section')

    // for(let i = 0;i < tabs.length;i++){
    //   tabs[i].onclick = function(){
    //     console.log(i);
    //     for(let i = 0;i < tabs.length;i++){
    //       tabs[i].classList.remove('active')
    //       contents[i].classList.remove('active')
    //     }
    //     this.classList.add('active')
    //     contents[i].classList.add('active')
    //   }
    // }

  // var没有块级作用域，要用一个自定义的属性存起来

    for(var i = 0;i < tabs.length;i++){
      tabs[i].index = i;
      tabs[i].onclick = function(){
        for(var i = 0;i < tabs.length;i++){
          tabs[i].classList.remove('active')
          contents[i].classList.remove('active')
        }
        this.classList.add('active')
        contents[this.index].classList.add('active')
      }
    }

  </script>
</body>

</html>